import React, { createContext, useContext, useEffect, useState } from 'react';

type Theme = 'light' | 'dark';

interface ThemeContextType {
	theme: Theme;
	toggleTheme: () => void;
	setTheme: (theme: Theme) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const useTheme = () => {
	const context = useContext(ThemeContext);
	if (context === undefined) {
		throw new Error('useTheme must be used within a ThemeProvider');
	}
	return context;
};

interface ThemeProviderProps {
	children: React.ReactNode;
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
	const [theme, setThemeState] = useState<Theme>(() => {
		// 从 localStorage 读取主题设置，默认为 light
    const savedTheme = localStorage.getItem('theme') as Theme;
    return savedTheme || 'dark';
	});

	useEffect(() => {
		// 更新 HTML 元素的 data-theme 属性
		document.documentElement.setAttribute('data-theme', theme);

		// 保存到 localStorage
		localStorage.setItem('theme', theme);
	}, [theme]);

	const toggleTheme = () => {
		setThemeState(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
	};

	const setTheme = (newTheme: Theme) => {
		setThemeState(newTheme);
	};

	const value: ThemeContextType = {
		theme,
		toggleTheme,
		setTheme,
	};

	return (
		<ThemeContext.Provider value={value}>
			{children}
		</ThemeContext.Provider>
	);
};